import logging

from command_parser.command_parser_container import CmdParserContainer
from command_parser.option_parser import *
from utils.common_utils import *
from command_parser.ar_parse.ar_command_generator import ARGenCommand

class ARParser(CmdParserContainer):
    
    def __init__(self, command=[], context=None, compiler="", options=[], cwd=""):
        self.command = command
        self.context = context
        self.compiler = compiler
        self.options = options
        self.cwd = cwd
        self.cmd_gen = ARGenCommand(context=context, cwd=self.cwd)
    
    def parse_command(self, command=[]):
        if not command:
            command = self.command
        
        self.compiler = command[0]
        argv = command[1:]
        self.options = self.build_options(parse_at_option(argv))
        
        self.compiler = real_binary_path(self.compiler)
        return self.compiler, self.options

    def build_options(self, raw_options=[]):
        plugins = []
        options = []
        files = []
        if raw_options[0][0] != '-':
            raw_options[0] = '-' + raw_options[0]
        i = 0

        while i < len(raw_options):
            item = raw_options[i]
            if item == '--plugin':
                if i+1 < len(raw_options):
                    plugins.append(raw_options[i+1])
                    i += 1
            elif item[0] == '-':
                options.append(item)
            else:
                files.append(item)
            i += 1

        options = ['-' + opt for opt in ''.join(options) if opt != '-']

        tag_plugins = [Option('--plugin', [plugin], PREFIX_SPACE) for plugin in plugins]

        tag_options = []
        for opt in options:
            if opt == '-a' or opt == '-b' or opt == '-N':
                tag_options.append(Option(opt, [files[0]], PREFIX_SPACE))
                del files[0]
            else:
                tag_options.append(Option(opt, [], PREFIX_SIMPLE))

        tag_files = [Option('', [file], PREFIX_MATCH) for file in files]
        return tag_options + tag_files + tag_plugins
    
    def get_input_options(self):
        base_inputs = []
        for item in self.options:
            if not item.option:
                base_inputs.append(item)
        base_inputs.pop(0)
        return base_inputs
    
    def get_output_options(self):
        
        base_output = []
        for item in self.options:
            if not item.option:
                base_output.append(item)
                break
        
        return base_output
    
    def get_original_command(self):
        return self.cmd_gen.generate_original_command(compiler=self.compiler, options=self.options)
    
    def get_maple_link_command(self):
        input_opts = self.get_input_options()
        output_opt = self.get_output_options()[0]
        
        return self.cmd_gen.generate_maple_link_command(compiler=self.context.MAPLE_BIN, input_options=input_opts, output_option=output_opt)